<?php

namespace App\Http\Controllers\UI;


use App\Miya\Models\Area;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use App\Miya\Models\SearchRecord;
use Diglactic\Breadcrumbs\Breadcrumbs;

class SearchController extends CommonController
{
    public function pc()
    {
        return view('tql::web.public.search', $this->buildData());
    }

    public function area(Area $area)
    {
        $data = $this->buildData();
        $data['area'] = $area;
        return view('tql::web.public.search', $data);
    }

    public function mobile()
    {
        return view('tql::wap.public.search', $this->buildData());
    }

    protected function buildData()
    {
        //添加搜索记录
        if (config('miya.search_record') && request()->has('wd')) {
            $record = [
                'search' => request()->input('wd'),
                'module_id' => request()->input('module'),
            ];

            $hash = md5(json_encode($record));
            $record['hash'] = $hash;

            $record = SearchRecord::firstOrCreate(['hash' => $hash], $record);
            $record->count += 1;
            $record->save();
        }

        $data = [];
        $data['area'] = new Area();
        $data['keywords'] = implode(',', miya('keyword')->list()->toArray());
        $data['description'] = null;
        $data['title'] = sprintf('搜索:%s_%s', request()->input('wd'), config('web.name'));

        $data['modules'] = Module::all();
        $infos = Info::with(Info::$DefaultRelationships)->where(function ($query) {
            $query->whereHas('classify')->where('status', 1)
                ->where(function ($query) {
                    $query->where('is_delayed', 2)->orWhere(function ($query) {
                        $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                    });
                });
            if (request()->has('module')) {
                $query->where('module_id', request()->input('module'));
            }
        })->where('name', 'like', '%' . request()->input('wd') . '%')
            ->orderBy('id', 'DESC')->paginate();
        // 格式化信息
        foreach ($infos as $info) {
            $info->avatar && $info->avatar = asset('uploads/' . $info->avatar);
            $info->images = array_map(function ($img) {
                return asset('uploads/' . $img);
            }, $info->images);
            $info->keywords = $info->getKeywords();
        }
        $data['infos'] = $infos;
        $data['breadcrumb'] = Breadcrumbs::render('search');

        return $data;
    }
}
